try:
	import matplotlib.pyplot as plt
        import matplotlib as mpl
except: 
        print "matplot not installed"
        pass
try:
        import numpy as np
except:
        print "numpy not installed"
	pass

#from randScene import *
from time import *
import csv
import os
import sys, random
import datetime
import math as math
threadAvgArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]
Ediff = [0,0,0,0,0,0,0]
diff =  [0,0,0,0,0,0,0]
threadSize = [16, 64, 128, 256, 512, 1024, 2048]
threadSize = [512]
primatives = ['scene_spheres', 'scene_boxes', 'scene_empty','scene_planes','scene_stress','scene_discs','scene_orig']
primatives = ['scene_stress', 'scene_orig']
avgArray = []
intArray = [] 		#used for graph
curdir = os.getcwd()[:-11] #subtract 'testingAuto to get working directory
print "current working dir: " + curdir +  "Initialized"
currentFileName = 'testing512.csv'
def runTests():
	fileWriter = csv.writer(open(curdir+currentFileName, 'w'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
	for primType in primatives:
		for threads in threadSize:
			for i in range(repeatAmount):
				cmd2 = (curdir+"src/ray %d "%(threads))				
				cmd3 = (curdir+"scenes/%s " %(primType))
				cmd4 = ' -verbose'
				cmdAll = cmd2+cmd3+cmd4	
                                print "Command: "+ cmdAll
				try:
					time1 = time()
					openDataOut = os.popen(cmdAll).read()
					print "File is printing: " +  openDataOut
					time2 = time()
					timefinal = time2-time1
				except:
					print "FAIL!"	
					pass

				writeThis = i, threads, primType, timefinal,'not-even'
#				writeToCsv(writeThis)

	                        fileWriter.writerow(writeThis)
	for primType in primatives:
		for threads in threadSize:
			for i in range(repeatAmount):
				cmd2 = (curdir+"src/ray %d "%(threads))				
				cmd3 = (curdir+"scenes/%s" %(primType))
                                cmd4 = " -verbose -even "
				cmdAll = cmd2+cmd3+cmd4	
				print cmdAll
				try:
					time1 = time()
					openDataOut = os.popen(cmdAll).read()
					print "File is printing: " +  openDataOut
					time2 = time()
					timefinal = time2-time1
				except:
					print "FAIL!"	
					pass
				writeThis = i,threads, primType, timefinal,'even'
				#writeToCsv(writeThis)
	                        fileWriter.writerow(writeThis)
	
def standardDev(arrayB):
	avgNum = average(arrayB)
	preSum = 0
	for element in arrayB:
		preSum = preSum +  pow((element-avgNum),2)
	stndDev = sqrt(preSum/avgNum)
	return stndDev

from math import sqrt
def sd(x):
	sd.sum  += x
	sd.sum2 += x*x
	sd.n    += 1.0
	sum, sum2, n = sd.sum, sd.sum2, sd.n
	return sqrt(sum2/n - sum*sum/n/n)
 

def average(combination):
	SampleSum = 0.0
	SampleCount = 0.0
	for elements in combination:	
		SampleSum = SampleSum+elements
		SampleCount = SampleCount+1
	SampleAvg = SampleSum/SampleCount
	return SampleAvg

def readFromCsv():
	sets = []
	fileReader = open(curdir+currentFileName,'r')
	print type(fileReader), fileReader
	print "reading from CSV"
	evenVar = "even\r\n"
	notEvenVar = "not-even\r\n"
	for Aline in fileReader:
		row = Aline.split(',')
	        print row	
		if int(row[1])==threadSize[0] and row[4]==notEvenVar:
			threadAvgArray[0] = threadAvgArray[0] + float(row[3])
		if int(row[1])==threadSize[1] and row[4]==notEvenVar:  	
			threadAvgArray[1] = threadAvgArray[1] + float(row[3])
		if int(row[1])==threadSize[2] and row[4]==notEvenVar:  	
			threadAvgArray[2] = threadAvgArray[2] + float(row[3])
		if int(row[1])==threadSize[3] and row[4]==notEvenVar:  	
			threadAvgArray[3] = threadAvgArray[3] + float(row[3])
		if int(row[1])==threadSize[4] and row[4]==notEvenVar:  	
			threadAvgArray[4] = threadAvgArray[4]+ float(row[3])
		if int(row[1])==threadSize[5] and row[4]==notEvenVar:  	
			threadAvgArray[5] = threadAvgArray[5]+ float(row[3])
		if int(row[1])==threadSize[6] and row[4]==notEvenVar:  	
			threadAvgArray[6] = threadAvgArray[6]+ float(row[3])
		if int(row[1])==threadSize[0] and row[4]==evenVar:  		
			threadAvgArray[7] = threadAvgArray[7]+ float(row[3])
		if int(row[1])==threadSize[1] and  row[4]==evenVar:  		
			threadAvgArray[8] = threadAvgArray[8]+ float(row[3])
		if int(row[1])==threadSize[2] and row[4]==evenVar:  		
			threadAvgArray[9] = threadAvgArray[9] + float(row[3])
		if int(row[1])==threadSize[3] and row[4]==evenVar:  	
			threadAvgArray[10] = threadAvgArray[10] + float(row[3])
		if int(row[1])==threadSize[4] and row[4]==evenVar:  	
			threadAvgArray[11] = threadAvgArray[11] + float(row[3])
		if int(row[1])==threadSize[5] and row[4]==evenVar:  	
			threadAvgArray[12] = threadAvgArray[12] + float(row[3])
		if int(row[1])==threadSize[6] and row[4]==evenVar:  	
			threadAvgArray[13] = threadAvgArray[13] + float(row[3])
		if row[2] not in sets:
			sets.append(row[2])
		numberOfIterations = row[0]
	print sets, "length: ", len(sets)
	i = 0
	for element in threadAvgArray:
		threadAvgArray[i]=element/((int(numberOfIterations)+1)*len(sets))
		i = i +1
	threadAvgHalfsies = int(math.floor(len(threadAvgArray)/2))

	print "\n\n Averaged values: ",threadAvgArray,"\n\n"	
	print "floor(len(threadAvgArray)/2: Half of the test data set: ", threadAvgHalfsies	
	for i in range(0,6):	
		diff[i] = threadAvgArray[i]-threadAvgArray[i+threadAvgHalfsies]
		Ediff[i] = 100*diff[i]/threadAvgArray[i]
		
	print "Values different: ",diff, "\n"

        print "Percent Difference: ", Ediff, "\n"	
	return diff, Ediff, threadAvgArray

def writeToCsv(element):
	print "Writing:  ",  element
	fileWriter.writerow(element)



if __name__=='__main__':
#def main():
	readString = 'n'
	graphString = 'n'
	repeatAmount = 0
        graphString = raw_input("would you like to graph, you will need matplotlib for python? y/n:  ")
        if graphString=='n':
            repeatAmount = int(raw_input("Number of iterations? "))
	if graphString == 'y':
	    diff, Ediff, threadAvgArray = readFromCsv()
            #plot()
	else:
	    runTests()
	
#	print threadAvgArray
#	threadAvgArray1 = threadAvgArray[:-7]
#	threadAvgArray2 = threadAvgArray[7:]
#        print "Avg of not even: " , threadAvgArray1, "\n"
#      print "Avg of even: ", threadAvgArray2, "\n"
	
#	stnd1 =	standardDev(threadAvgArray1)
#	stnd2 = standardDev(threadAvgArray2)
#	print "StndDev thrdAvgNot-Even: ", stnd1
#	print "StndDev thrdAvgEven: ",  stnd2
	#for value in threadAvgArray1:
#		print (value, sd(value))
#	for value in threadAvgArray2:
#		print (value, sd(value))
#	for value in diff:
#		print (value, sd(value))



#main()


